import { useSetState, useUpdateEffect } from 'ahooks';
import useHeatMap from '@/utils/marketingMap/useHeatMap';
import { store_icon } from '@/utils/marketingMap/utils';

const useMap = (data: any, isAuth: boolean) => {
  const [state, setState] = useSetState<any>({});
  const { map, AMap, infoWindow } = state;
  const { heatMap, setHeatMapData } = useHeatMap(AMap, map);
  const onRenderingCompleted = (map: any, AMap: any) => {
    const infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(0, -20),
      closeWhenClickMap: true,
      autoMove: true,
    });
    setState({ map, AMap, infoWindow });
  };

  const markerClick = (content: string, position: any) => {
    infoWindow.setContent(content);
    infoWindow.open(map, position);
  };
  useUpdateEffect(() => {
    if (map && heatMap && data) {
      const { storeData, distributionData } = data || {};

      if(!storeData?.lon || !storeData?.lat) return
      map.clearMap();

      map.setCenter([storeData.lon, storeData.lat]);

      const labelMarker = new AMap.LabelMarker({
        position: [storeData.lon, storeData.lat],
        icon: store_icon,
        zIndex: 999,
      });

      const content = new AMap.Marker({
        position: [storeData.lon, storeData.lat],
        content: `
            <div class="infoWindow">
              <span>${isAuth ? storeData.name : '我的专营店'}</span>
            <div/>
          `,
        offset: new AMap.Pixel(-50, -65), // 偏移位置
      });
      const heatMapData = distributionData.map(
        (item: { lon: string; lat: string; vehicleCount: number }) => ({
          lng: item.lon,
          lat: item.lat,
          count: item.vehicleCount,
        }),
      );
      setHeatMapData(heatMapData);

      map.add(labelMarker);
      map.add(content);
    } else {
      map?.clearMap();
      setHeatMapData([]);
    }
  }, [data, heatMap, map, isAuth]);

  return { map, markerClick, onRenderingCompleted };
};

export default useMap;
